package com.datatraffic.salesup;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.datatraffic.salesup.model.Task;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnClosedListener;


public class MapaActivity extends FragmentActivity implements ConsumidorServicios{
	
	private LocationManager locationManager;
	private GoogleMap mMap;
	private Location lastlocation;
	private boolean gpsubicado;
	private boolean centrado;
	public static final int CALLER_DECKPICKER = 3;
	private Button mBtnFind;
	private EditText etPlace;
	private LatLng destino = null;
	private static boolean mChanged = false;
	public static final int SIGNATURE_ACTIVITY = 1;

	private ImageView logo;
	private boolean visible=false;
	public static final String EXTRA_CALLER = "CALLER";
	private ImageView inf,toDo;
	private int mCaller;
	private SlidingMenu menu;
	private ListAdapterTasks adapter;
	private ProgressDialog pd;
	
	
	protected void onCreate(Bundle paramBundle) {
		try {
			super.onCreate(paramBundle);
			this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
	        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.mapa);

			centrado = false;
			
		
			try {
				SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager()
						.findFragmentById(R.id.map);

				this.mMap = fm.getMap();
				this.mMap.getUiSettings().setZoomControlsEnabled(false);
				this.mMap.getUiSettings().setZoomGesturesEnabled(true);
				this.mMap.getUiSettings().setCompassEnabled(false);
				this.mMap.getUiSettings().setMyLocationButtonEnabled(true);
				this.mMap.getUiSettings().setScrollGesturesEnabled(true);
			} catch (Exception e) {
			}

			try {
				locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
				if (locationManager
						.isProviderEnabled(locationManager.NETWORK_PROVIDER)) {
					Criteria criteria = new Criteria();
					locationManager.requestLocationUpdates(
							LocationManager.NETWORK_PROVIDER, 2000, 0,
							onLocationChange);
					String provider = locationManager.getBestProvider(criteria,
							false);
					lastlocation = locationManager
							.getLastKnownLocation(provider);
					centrarCamara();
				}
				if (locationManager
						.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
					Criteria criteria = new Criteria();
					locationManager.requestLocationUpdates(
							LocationManager.GPS_PROVIDER, 2000, 0,
							onLocationChange);
					String provider = locationManager.getBestProvider(criteria,
							false);
					Location location = locationManager
							.getLastKnownLocation(provider);
					lastlocation = location;
					centrarCamara();
				}
			} catch (Exception e) {
			}
			
		} catch (Exception e) {
			Log.i("Carajin", e.getMessage(), e);
		}
		
		
		mBtnFind = (Button) findViewById(R.id.button1Map);
		logo = (ImageView) findViewById(R.id.imageView2Map);
		etPlace = (EditText) findViewById(R.id.editText1);
		
		etPlace.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {	
				// Getting the place entered
				logo.setVisibility(View.INVISIBLE);
				visible=true;

			}
		});
		
		// Setting click event listener for the find button
		mBtnFind.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {	
				// Getting the place entered 

				Log.v("onClick", "onClick call");
				String location = etPlace.getText().toString();

				if(location==null || location.equals("")){
					Toast.makeText(getBaseContext(), "No Place is entered", Toast.LENGTH_SHORT).show();
					return;
				}

				try {
					// encoding special characters like space in the user input place
					location = URLEncoder.encode(location, "utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

				
				String address = location;
				String urlNew="https://maps.googleapis.com/maps/api/geocode/json?address="+address+"&components=country:CO&sensor=false";

				// Instantiating DownloadTask to get places from Google Geocoding service
				// in a non-ui thread
				DownloadTask downloadTask = new DownloadTask();

				// Start downloading the geocoding places
				downloadTask.execute(urlNew);



			}
		});
		
		mMap.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
            	if(destino!=null)
            	{
            		double lat = lastlocation.getLatitude();
					double lng = lastlocation.getLongitude();
					LatLng origen = new LatLng(lat, lng);
            		// Getting URL to the Google Directions API
					String url = getDirectionsUrl(origen, destino);				
					
					DownloadTaskDir downloadTask = new DownloadTaskDir();
					
					// Start downloading json data from Google Directions API
					downloadTask.execute(url);
            	}



            }
        });
		
		inf = (ImageView) this.findViewById(R.id.imageView1Map);
		inf.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
				
			}
		});
		
		toDo = (ImageView) this
				.findViewById(R.id.hacer);
		toDo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				menu.showMenu();
				mostrarMenuPrincipal(null);
			}
		});
		
		// sliding
		menu = new SlidingMenu(MapaActivity.this);
		menu.setMode(SlidingMenu.RIGHT);
		menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
		menu.setShadowWidthRes(R.dimen.shadow_width);
		menu.setShadowDrawable(R.drawable.shadowslidemenu);
		menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		menu.setFadeEnabled(true);
		menu.setFadeDegree(0.35f);
		menu.setBackgroundResource(android.R.color.white);
		menu.attachToActivity(MapaActivity.this, SlidingMenu.SLIDING_CONTENT);
		menu.setOnClosedListener(new OnClosedListener() {

			@Override
			public void onClosed() {
				mostrarMenuPrincipal(null);
			}
		});

	

	}
	
	public void mostrarMenuPrincipal(View button) {
		menu.setMenu(R.layout.menu_principal);
		JSONObject request = new JSONObject();
		/*try {
			request.put("function", "selectList");
			request.put("mobile_key", "");
			request.put("resource", "");
			request.put("query", "");
			request.put("order", "");
			request.put("mode", "");
			Log.d("request", request.toString());
			
			
			pd = new ProgressDialog(MapaActivity.this);
    		pd.setCancelable(false);
			pd.setMessage("Actualizando tareas, por favor espere un momento!!!");
			pd.show();
			ManagerExecutor executor = new ManagerExecutor(MapaActivity.this, MapaActivity.this.getBaseContext());
    		executor.execute(request);
		} catch (JSONException e) {
			Toast.makeText(getApplicationContext(),
					"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
			e.printStackTrace();
		}*/
		Task data[] = new Task[3];
        try {
			request=new JSONObject("{id:10,title:visitajuanamadeo,direccion:xxxx}");		
			JSONArray bla=new JSONArray();
			bla.put(request);
			request=new JSONObject("{id:11,title:visitafranciscogarcia,direccion:avpepesierra}");	
			bla.put(request);
			request=new JSONObject("{id:12,title:visitajulianrodriguez,direccion:dg34bis18}");	
			bla.put(request);
			for(int i=0;i<bla.length();i++)
			{
				JSONObject xx=bla.getJSONObject(i);
				Task t=new Task();
				t.setDescripcion(xx.getString("title"));
				t.setTarea(xx.getString("direccion"));
				data[i]=t; 
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		/*adapter = new ListAdapterTasks(MapaActivity.this,R.layout.listview_item_row_tasks, data);
		ListView  listView1 = (ListView)menu.findViewById(R.id.listViewTareas);
		//View header = (View)getLayoutInflater().inflate(R.layout.listview_item_row_tasks, null);
		//listView1.addHeaderView(header);

		listView1.setAdapter(adapter);
		// ListView Item Click Listener
		listView1.setOnItemClickListener(new OnItemClickListener() {

              @Override
              public void onItemClick(AdapterView<?> parent, View view,
                 int position, long id) {
            	  
            	// Add action item
          		ActionItem addAction = new ActionItem();

          		addAction.setTitle("Phone");
          		addAction.setIcon(getResources().getDrawable(R.drawable.phone));

          		// Accept action item
          		ActionItem accAction = new ActionItem();

          		accAction.setTitle("Gmail");
          		accAction.setIcon(getResources().getDrawable(R.drawable.gmail));

          		// Upload action item
          		ActionItem upAction = new ActionItem();

          		upAction.setTitle("Talk");
          		upAction.setIcon(getResources().getDrawable(R.drawable.gmail));
          		
          		ActionItem upAction2 = new ActionItem();

          		upAction2.setTitle("PHONE");
          		upAction2.setIcon(getResources().getDrawable(R.drawable.phone));
          		
          		ActionItem upAction3 = new ActionItem();

          		upAction3.setTitle("PHONE XXX");
          		upAction3.setIcon(getResources().getDrawable(R.drawable.gmail));
          		
          		ActionItem upAction4 = new ActionItem();

          		upAction4.setTitle("PHONE SSS");
          		upAction4.setIcon(getResources().getDrawable(R.drawable.phone));

          		final QuickAction mQuickAction = new QuickAction(MapaActivity.this);

          		mQuickAction.addActionItem(addAction);
          		mQuickAction.addActionItem(accAction);
          		mQuickAction.addActionItem(upAction);
          		mQuickAction.addActionItem(upAction2);
          		mQuickAction.addActionItem(upAction3);
          		mQuickAction.addActionItem(upAction4);
          		
          		mQuickAction.show(view);
				mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER);

                
              }

         }); */

	}
		
	static LatLng COORDENA = null;

	private void centrarCamara() {

		int status = GooglePlayServicesUtil
				.isGooglePlayServicesAvailable(getApplicationContext());
		if (status == ConnectionResult.SUCCESS) {
			try {
				if (lastlocation != null) {
					
					mMap.clear();
					double lat = lastlocation.getLatitude();
					double lng = lastlocation.getLongitude();
					LatLng coordinate = new LatLng(lat, lng);
					COORDENA=coordinate;
					centrado=true;
					Marker marcador = mMap.addMarker(new MarkerOptions().position(COORDENA)
					        .title("Usted se encuentra aqui"));
					
					mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(COORDENA, 18));
				    // Zoom in, animating the camera.
					mMap.animateCamera(CameraUpdateFactory.zoomTo(18), 2000, null);
					
				}
				
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private boolean estaGPSActivado() {
		final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)
				|| manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
			return true;
		} else
			return false;
	}



	LocationListener onLocationChange = new LocationListener() {
		public void onLocationChanged(Location loc) {
			lastlocation = loc;
			gpsubicado = true;
			
			if (mMap != null) {
				mMap.clear();
				LatLng position = new LatLng(loc.getLatitude(),
						loc.getLongitude());
				//mMap.addMarker(new MarkerOptions().position(position).icon(
				//		BitmapDescriptorFactory
				//				.fromResource(R.drawable.marcador)));
				centrarCamara();
			}
			
		}

		public void onProviderDisabled(String provider) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	};

	@Override
	public void onPause() {
		super.onPause();
		
			//locationManager.removeUpdates(onLocationChange);
			//finish();
	}

	@Override
	public void onResume() {
		super.onResume();
		centrado = false;
		try {
			locationManager
					.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
							5000, 0, onLocationChange);
		} catch (Exception e) {
			Log.e("DEMO", "No NETWORK PROVIDER", e);
		}
		try {
			locationManager.requestLocationUpdates(
					LocationManager.GPS_PROVIDER, 5000, 0, onLocationChange);
		} catch (Exception e) {
			Log.e("DEMO", "No GPS PROVIDER", e);
		}
	}

	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
	
	}

	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		gpsubicado = savedInstanceState.getBoolean("gpsubicado");
	}
	
	private String downloadUrl(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
                URL url = new URL(strUrl);


                // Creating an http connection to communicate with url 
                urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuffer sb  = new StringBuffer();

                String line = "";
                while( ( line = br.readLine())  != null){
                        sb.append(line);
                }

                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
                urlConnection.disconnect();
        }

        return data;
        
	}

	
	 /** A class, to download Places from Geocoding webservice */
    private class DownloadTask extends AsyncTask<String, Integer, String>{

            String data = null;

            // Invoked by execute() method of this object
            @Override
            protected String doInBackground(String... url) {
                    try{                    		
                            data = downloadUrl(url[0]);
                    }catch(Exception e){
                             Log.d("Background Task",e.toString());
                    }
                    return data;
            }

            // Executed after the complete execution of doInBackground() method
            @Override
            protected void onPostExecute(String result){
            		
            		ParserTask parserTask = new ParserTask();
                    parserTask.execute(result);
            }

    }

  
	class ParserTask extends AsyncTask<String, Integer, List<HashMap<String,String>>>{

		JSONObject jObject;
		
		
		@Override
		protected List<HashMap<String,String>> doInBackground(String... jsonData) {
		
			List<HashMap<String, String>> places = null;			
			GeocodeJSONParser parser = new GeocodeJSONParser();
        
	        try{
	        	jObject = new JSONObject(jsonData[0]);
	        	
	            /** Getting the parsed data as a an ArrayList */
	            places = parser.parse(jObject);
	            
	        }catch(Exception e){
	                Log.d("Exception",e.toString());
	        }
	        return places;
		}
		
		// Executed after the complete execution of doInBackground() method
		@Override
		protected void onPostExecute(List<HashMap<String,String>> list){			
			
		
			/*for(int i=0;i<list.size();i++){
			
				// Creating a marker
	            MarkerOptions markerOptions = new MarkerOptions();
	            HashMap<String, String> hmPlace = list.get(i);
	
	            double lat = Double.parseDouble(hmPlace.get("lat"));	            
	            double lng = Double.parseDouble(hmPlace.get("lng"));
	           
	            String name = hmPlace.get("formatted_address");
	            LatLng latLng = new LatLng(lat, lng);
	            markerOptions.position(latLng);
	            markerOptions.title(name);
                destino=latLng;
	            mMap.addMarker(markerOptions);    
	            
	            // Locate the first location
                if(i==0)
                	mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

                
            }*/
			
			// Creating a marker
			MarkerOptions markerOptions = new MarkerOptions();
			if(list.size()>0)
			{
				HashMap<String, String> hmPlace = list.get(0);

				double lat = Double.parseDouble(hmPlace.get("lat"));	            
				double lng = Double.parseDouble(hmPlace.get("lng"));

				String name = hmPlace.get("formatted_address");
				LatLng latLng = new LatLng(lat, lng);
				markerOptions.position(latLng);
				markerOptions.title(name);
				destino=latLng;
				mMap.addMarker(markerOptions);    
				mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
				locationManager.removeUpdates(onLocationChange); 
			}
			else
			{
				Toast.makeText(MapaActivity.this, "No se encontro ningun resultado!!", Toast.LENGTH_LONG).show();;

			}
		}
	}
	
	
	//PINTAR LA LINEA
	
	
	private String getDirectionsUrl(LatLng origin,LatLng dest){
		
		// Origin of route
		String str_origin = "origin="+origin.latitude+","+origin.longitude;
		
		// Destination of route
		String str_dest = "destination="+dest.latitude+","+dest.longitude;		
		
					
		// Sensor enabled
		String sensor = "sensor=false";			
					
		// Building the parameters to the web service
		String parameters = str_origin+"&"+str_dest+"&"+sensor;
					
		// Output format
		String output = "json";
		
		// Building the url to the web service
		String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;// ACA SE PODRIA
		
		
		return url;
	}
	
	/** A method to download json data from url */
    private String downloadUrlDir(String strUrl) throws IOException{
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try{
                URL url = new URL(strUrl);

                // Creating an http connection to communicate with url 
                urlConnection = (HttpURLConnection) url.openConnection();

                // Connecting to url 
                urlConnection.connect();

                // Reading data from url 
                iStream = urlConnection.getInputStream();

                BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                StringBuffer sb  = new StringBuffer();

                String line = "";
                while( ( line = br.readLine())  != null){
                        sb.append(line);
                }
                
                data = sb.toString();

                br.close();

        }catch(Exception e){
                Log.d("Exception while downloading url", e.toString());
        }finally{
                iStream.close();
                urlConnection.disconnect();
        }
        return data;
     }
    
 // Fetches data from url passed
 	private class DownloadTaskDir extends AsyncTask<String, Void, String>{			
 				
 		// Downloading data in non-ui thread
 		@Override
 		protected String doInBackground(String... url) {
 				
 			// For storing data from web service
 			String data = "";
 					
 			try{
 				// Fetching the data from web service
 				data = downloadUrlDir(url[0]);
 			}catch(Exception e){
 				Log.d("Background Task",e.toString());
 			}
 			return data;		
 		}
 		
 		// Executes in UI thread, after the execution of
 		// doInBackground()
 		@Override
 		protected void onPostExecute(String result) {			
 			super.onPostExecute(result);			
 			
 			ParserTaskDir parserTask = new ParserTaskDir();
 			
 			// Invokes the thread for parsing the JSON data
 			parserTask.execute(result);
 				
 		}		
 	}
 	
 	/** A class to parse the Google Places in JSON format */
    private class ParserTaskDir extends AsyncTask<String, Integer, List<List<HashMap<String,String>>> >{
    	
    	// Parsing the data in non-ui thread    	
		@Override
		protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
			
			JSONObject jObject;	
			List<List<HashMap<String, String>>> routes = null;			           
            
            try{
            	jObject = new JSONObject(jsonData[0]);
            	DirectionsJSONParser parser = new DirectionsJSONParser();
            	
            	// Starts parsing data
            	routes = parser.parse(jObject);    
            }catch(Exception e){
            	e.printStackTrace();
            }
            return routes;
		}
		
		// Executes in UI thread, after the parsing process
		@Override
		protected void onPostExecute(List<List<HashMap<String, String>>> result) {
			ArrayList<LatLng> points = null;
			PolylineOptions lineOptions = null;
			MarkerOptions markerOptions = new MarkerOptions();
			
			// Traversing through all the routes
			for(int i=0;i<result.size();i++){
				points = new ArrayList<LatLng>();
				lineOptions = new PolylineOptions();
				
				// Fetching i-th route
				List<HashMap<String, String>> path = result.get(i);
				
				// Fetching all the points in i-th route
				for(int j=0;j<path.size();j++){
					HashMap<String,String> point = path.get(j);					
					
					double lat = Double.parseDouble(point.get("lat"));
					double lng = Double.parseDouble(point.get("lng"));
					LatLng position = new LatLng(lat, lng);	
					
					points.add(position);						
				}
				
				// Adding all the points in the route to LineOptions
				lineOptions.addAll(points);
				lineOptions.width(2);
				lineOptions.color(Color.RED);	
				
				if(visible==true)
				{
					logo.setVisibility(View.VISIBLE);
					visible=false;
					etPlace.setText("");
				}
				
			}
			
			// Drawing polyline in the Google Map for the i-th route
			mMap.animateCamera( CameraUpdateFactory.zoomTo( 14 ) );  
			mMap.addPolyline(lineOptions);	
		}			
    }


	@Override
	public void procesarRespuesta(JSONObject json) {
		// TODO Auto-generated method stub
		
		if (pd != null && pd.isShowing()) {
			pd.dismiss();
		}
		String result;
		try {
			result = json.optString("error");
			if(result.trim().equalsIgnoreCase("false"))
			{
				JSONArray datos1=json.optJSONArray("data");
				Task respuestas[]= new Task[datos1.length()];
				for (int i = 0; i < datos1.length(); i++) {
					JSONObject aux;
					Task temp = new Task();
					try {
						aux = datos1.getJSONObject(i);
						temp = new Task(aux);
					} catch (JSONException e) {
						e.printStackTrace();
					}			
					respuestas[i] = temp;
				}

				final ListView listView = (ListView) menu.findViewById(R.id.listViewTareas);
				adapter = new ListAdapterTasks(MapaActivity.this,R.layout.listview_item_row_tasks, respuestas);
				listView.setAdapter(adapter);

			}
			else
			{
				Toast.makeText(getApplicationContext(),
						"Ocurrio un error contactando al servidor.", Toast.LENGTH_LONG).show();
			}

		}
		catch (Exception e)
		{
			e.printStackTrace();
			Toast.makeText(getApplicationContext(),"Ocurrio un error en el servicio.", Toast.LENGTH_LONG).show();
		}
		
	} 
	
}